﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using BLL;
using POS.Framework;
using Model.Bill;
using BLL.Enums;
using DevExpress.Utils;
using DevExpress.Xpo;
using Model;
using POS.UserControl.Dialog;
using DevExpress.Data.Filtering;
using System.Collections;

namespace POS.ModForm.Sale
{
    public partial class frmDeliverySale : DevExpress.XtraEditors.XtraForm
    {
        Session s=null;
        WarehouseBLL warehouseBLL = new WarehouseBLL();
        ProductBLL productBLL = new ProductBLL();
        OrderBLL orderBLL = new OrderBLL();
        OrderDetailBLL orderDetailBLL = new OrderDetailBLL();
        MyGridChedkMarksSelectionHelper ChedkSelect { get; set; }
        TB_Order order = null;
        string orderRemark = string.Empty;
        public frmDeliverySale()
        {
            InitializeComponent();
        }

        private void frmDeliverySale_Load(object sender, EventArgs e)
        {
            using (WaitDialogForm wdf = new WaitDialogForm(MsgBox.WaitLoading))
            {
                s = DatabaseSchema.Session;
                this.gridView.CustomDrawRowIndicator += new DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventHandler(SpecialGridView.DrawRowIndicator);
                this.ChedkSelect = new MyGridChedkMarksSelectionHelper(this.gridView);
                SetButtonClickEvent();
                this.repositoryItemLookUpEditUnit.DataSource = EnumManage.GetDictionaryEntry(typeof(ProductType));
                wdf.Close();
            }
        }
        void SetButtonClickEvent()
        {
            this._SellDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
            addItemSaleUC.AddDetail.Click += new EventHandler(AddDetail);
            addItemSaleUC.DelDetail.Click += new EventHandler(btnDelete_Click);
            addItemSaleUC.SellPriceControl.KeyPress += new KeyPressEventHandler(SellPriceControl_KeyPress);
            addItemSaleUC.InitBindWarehouse();
            addItemSaleUC.LookUpProduct.Properties.DataSource = productBLL.GetProducts();
            addItemSaleUC.LookUpProduct.Select();
        }
        void AddDetail(object sender, EventArgs e)
        {
            try
            {
                s.BeginTransaction();
                if (order == null)
                {
                    order = new TB_Order(s);
                    order.OrderID = PlanIDBLL.GetPlanID(s,"XS", this._SellDate.Text.Trim());
                    order.BillCode = order.OrderID;
                    order.StoreID = s.FindObject<B_Store>(CriteriaOperator.Parse("StoreCode=?", MemberInfo.StoreCode));
                    order.SellDate = Convert.ToDateTime(this._SellDate.Text);
                    order.Remark = orderRemark;
                    order.TypeID = (int)OrderType.Delivery;
                    order.ProviderID = s.GetObjectByKey<B_Provider>(this.ProviderID);
                    order.ContactUser = this._ContactUser.Text;
                    order.ContactPhone = this._ContactPhone.Text;
                    order.Save();
                }
                orderDetailBLL.Add(order, addItemSaleUC.WarehouseID, addItemSaleUC.ProductID, ProductType.Nothing, addItemSaleUC.Quantity, addItemSaleUC.SellPrice);
                s.CommitTransaction();
                tableLayoutPanel1.Enabled = false;
            }
            catch (Exception ex)
            {
                s.RollbackTransaction();
                throw ex;
                //MsgBox.ShowWarning(ex.Message);
                return;
            }
            order.OrderDetails.Reload();
            this.gridControl.DataSource = order.OrderDetails;
            ShowOrderUI();
            MsgBox.ShowTips("添加销售单明细成功！");
            addItemSaleUC.ControlResetText();
        }
        void btnDelete_Click(object sender, EventArgs e)
        {
            if (this.ChedkSelect.SelectedCount <= 0)
            {
                MsgBox.ShowWarning("请选中要删除的货品!");
                return;
            }
            try
            {
                foreach (TB_OrderDetail od in this.ChedkSelect._Selection)
                {
                    if (od != null)
                        od.Delete();
                }
                orderBLL.CalcOrderAmount(order);
            }
            catch (Exception ex)
            {
                MsgBox.ShowWarning(ex.Message);
                return;
            }
            order.OrderDetails.Reload();
            this.gridControl.DataSource = order.OrderDetails;
        }
        void SellPriceControl_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (addItemSaleUC.SellPriceControl.Properties.Mask.MaskType != DevExpress.XtraEditors.Mask.MaskType.Numeric)
            {
                addItemSaleUC.SellPriceControl.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric;
                addItemSaleUC.SellPriceControl.Properties.Mask.EditMask = "f2"; ;
                addItemSaleUC.SellPriceControl.Properties.Mask.UseMaskAsDisplayFormat = true;
            }
            if (e.KeyChar == 13)
                AddDetail(sender, e);
        }
        void ShowOrderUI()
        {
            if (order == null)
            {
                this._SellDate.Text = DateTime.Now.ToShortDateString();
                //this._CopeAmount.Text = "0.00￥";
                //this._ActualAmount.Text = "0.00￥";
                //this._ckGifts.Checked = false;
                this.groupControl1.Text = "送货销售单基本信息";
                this.ProviderID = string.Empty;
                tableLayoutPanel1.Enabled = true;
                this.gridControl.DataSource = null;
            }
            else
            {
                this._SellDate.Text = order.SellDate.ToShortDateString();
                //this._CopeAmount.Text = order.CopeAmount.ToString("f2") + "￥";
                //this._ActualAmount.Text = order.ActualAmount.ToString("f2") + "￥";
                this.groupControl1.Text = string.Format("销售单号：{0}  状态：{1}", order.BillCode, EnumManage.GetBillStatus(typeof(OrderStatus), order.StatusID));
            }
        }
        private void btnDeliveryIn_Click(object sender, EventArgs e)
        {
            if (order == null || order.StatusID != (int)OrderStatus.Editor)
            {
                MsgBox.ShowWarning("销售单不在'编辑'状态,不能进行送货！");
                return;
            }
            if (order.OrderDetails.Count == 0)
            {
                MsgBox.ShowWarning("销售单没有明细！");
                return;
            }
            if (MsgBox.ShowYesNoAndWarning("送货将进行减少库存,你确定送出的货品明细吗！") == System.Windows.Forms.DialogResult.Yes)
            {
                try
                {
                    string msg = orderBLL.PaymentDelivery(order);
                    if (string.IsNullOrEmpty(msg))
                    {
                        MsgBox.ShowTips("送货执行成功,送货完成后请进行结单！");
                        this.order = null;
                        ShowOrderUI();
                    }
                    else
                    {
                        MsgBox.ShowWarning(msg);
                    }
                }
                catch (Exception ex)
                {
                    MsgBox.ShowWarning(ex.Message);
                }
            }
        }
        string ProviderID = string.Empty;
        private void btnProvider_ButtonPressed(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            using (frmPopProvider fpp = new frmPopProvider()) 
            {
                if (fpp.ShowDialog() == DialogResult.OK) 
                {
                    B_Provider fProvider = fpp.GetSelectRow();
                    ProviderID = fProvider.ProviderID;
                    this.btnProvider.Text = fProvider.ProviderName;
                    using (WaitDialogForm wdf = new WaitDialogForm("正在加载客户的购买记录和欠款记录..."))
                    {
                        if (string.IsNullOrEmpty(_ContactUser.Text.Trim()) && string.IsNullOrEmpty(_ContactPhone.Text.Trim()))
                        {
                            XPCollection<B_ProviderContact> pcs = new DevExpress.Xpo.XPCollection<B_ProviderContact>(s, CriteriaOperator.Parse("ProviderID=?", fProvider.ProviderID));
                            foreach (B_ProviderContact pc in pcs)
                            {
                                    _ContactUser.Text = pc.ContactName;
                                    _ContactPhone.Text = pc.Phone;
                                    break;
                            }
                        }
                        //object amount = s.Evaluate<TB_Order>(CriteriaOperator.Parse("SUM(CopeAmount-ActualAmount)"), CriteriaOperator.Parse("ProviderID=? And PayStatusID!=?", fProvider.ProviderID, (int)PaymentStatus.Complete));
                        //if (amount != null)
                        //    this.lblAmount.Text = "客户欠款金额：" + Convert.ToDateTime(amount).ToString("f2");
                        XPCollection<TB_OrderDetail> od = new DevExpress.Xpo.XPCollection<TB_OrderDetail>(s, CriteriaOperator.Parse("OrderID.ProviderID=?", fProvider.ProviderID));
                        od.Sorting.Add(new DevExpress.Xpo.SortProperty("OrderID", DevExpress.Xpo.DB.SortingDirection.Descending));
                        od.TopReturnedObjects = 30;
                        this.gridViewBuy.GridControl.DataSource = od;
                        DevExpress.Xpo.XPCollection<TB_Order> or = new DevExpress.Xpo.XPCollection<TB_Order>(s, CriteriaOperator.Parse("ProviderID=? And PayStatusID=? And StatusID=?", fProvider.ProviderID, (int)PaymentStatus.Complete, (int)OrderStatus.Complete));
                        or.Sorting.Add(new DevExpress.Xpo.SortProperty("OrderID", DevExpress.Xpo.DB.SortingDirection.Descending));
                        or.TopReturnedObjects = 30;
                        this.gridViewOrder.GridControl.DataSource = or;
                        wdf.Close();
                    }
                }
            }
        }
        private void btnMakeUp_Click(object sender, EventArgs e)
        {
            if (order != null)
            {
                if (MsgBox.ShowYesNoCancelAndTips("是否要清除当前单据的信息！") == System.Windows.Forms.DialogResult.Yes)
                {
                    order = null;
                    this.gridControl.DataSource = null;
                    ShowOrderUI();
                }
                else
                {
                    return;
                }
            }
            using (frmMend fpm = new frmMend())
            {
                if (fpm.ShowDialog() == System.Windows.Forms.DialogResult.Yes)
                {
                    this._SellDate.Text = fpm.SellDate;
                    this.orderRemark = fpm.Remark;
                }
            }
        }
        private void btnPayMent_Click(object sender, EventArgs e)
        {
            using (frmPopDelivery popDelivery = new frmPopDelivery())
            {
                popDelivery.ShowDialog();
            }
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (order != null && order.OrderDetails.Count > 0)
            {
                if (MsgBox.ShowYesNoAndWarning("送货销售已生成，是否要取消订单!") == System.Windows.Forms.DialogResult.Yes)
                {
                    this.Close();
                }
            }
            else
            {
                this.Close();
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (order != null) 
            {
                Hashtable lst=new Hashtable();
                DataTable dt = orderBLL.Print(order, out lst);
                SpecialGridView.PrintBill("送货订单打印模板.mb", lst, dt);
                return;
            }
            MsgBox.ShowTips("送货订单信息已清空,请到列表页进行打印！");
        }
    }
}